<template>
  <ul class="sidebar">
    <li v-for="(item, index) in navItems"
        class="baritem" :class="{active: selIndex === index}" 
        :key="item.name"
        @click="itemClick(item, index)">
        {{item.title}}</li>
  </ul>
</template>

<script>
import {ref, onMounted, nextTick} from 'vue'
import {useRouter} from 'vue-router'

export default {
  name: 'NavSideBar',
  props: {
    navItems: Array
  },
  setup(props) {
    const router = useRouter()

    let selIndex = ref(0)

    const itemClick = ((item, index) => {
      selIndex.value = index
      router.push(item.path)
    })

    function adjSelectedIndex(){
      let route = router.currentRoute
      if (route && selIndex.value < props.navItems.length && props.navItems[selIndex.value].path !== route.value.path) {
        let currpath = route.value.path
        let idx = props.navItems.findIndex(function(value, index, arr){
          return value.path === currpath || currpath.indexOf(value.path) === 0
        })
        if (idx >= 0) {
          console.log('adjust selected index')
          selIndex.value = idx
        }
      }
    }

    onMounted(() => {
      router.afterEach((to, from) => {
        adjSelectedIndex() //run it when user refresh the web page manually
      })

      adjSelectedIndex()   //run it when Webpack refresh the current web page automatically
    })

    return {
      selIndex,
      itemClick
    }
  },
}
</script>

<style scoped>

  .baritem {
    height: 30px;
    font-size: 18px;
    list-style-type: none;
    padding-left: 7px;
  }

  .baritem:hover {
    background-color: #e9abf5;
    color: navy;
    font-weight: bold;
    cursor: pointer;
  }

  .baritem.active {
    color: seagreen;
    font-weight: bold;
  }

  .sidebar{
    position: relative;
    width: calc(100% - 20px);
    height: calc(100% - 20px);
    left: 0;
    top: 0;
    overflow: auto;
    padding: 5px 5px 5px 10px;
    margin: 0;
  }

</style>